<!-- AI模板 -->
<template>
  <div>
    <div>
      <div style="display:flex;justify-content:space-between;">
        <partitionTree :nodeData="nodeData" :defaultProps="defaultProps" :dialogName="'软件分类'"
          @handleNodeClick="handleNodeClick" @submitTemplete="submitTemplete" @deleteNode="deleteNode" ref="partitionTree"
          @toggleVisibility="toggleVisibility"
          minHeight="calc(100vh - 142px)"></partitionTree>
        <div :style="{ width: containerWidth }" class="box"
          style="background:#fff;padding:16px;border: 1px solid #ddd;border-radius: 4px;box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.1);">
          <!-- <el-button type="primary" @click="addModer">添加软件</el-button> -->
          <el-button type="primary" @click="reviseStart">批量修改</el-button>
          <el-table stripe border :data="tableData" style="width: 100%; margin-top: 15px">
            <el-table-column label="序号" width="80" type="index"
              :index='(index) => { return (index + 1) + (pageNum - 1) * pageSize }'> </el-table-column>
            <el-table-column label="软件分类" prop="Class" width="120" show-overflow-tooltip></el-table-column>
            <el-table-column label="软件名称" prop="Descp" show-overflow-tooltip></el-table-column>
            <el-table-column label="软件版本" prop="Version" width="180" show-overflow-tooltip></el-table-column>
            <el-table-column label="发布厂商" prop="Factory" show-overflow-tooltip></el-table-column>
            <el-table-column label="操作系统" prop="OSClass" width="120" show-overflow-tooltip></el-table-column>
            <el-table-column label="系统类型" prop="OSType" width="120" show-overflow-tooltip>
              <template slot-scope="{row}">
                <span>{{ row.OSType === '' ? '全部' : row.OSType }}</span>
              </template>
            </el-table-column>
            <el-table-column label="软件类型" prop="Property" width="120" show-overflow-tooltip>
              <template slot-scope="{row}">
                <span v-if="row.Property">{{ row.Property === 1 ? '必装软件' : row.Property === 2 ? '非法软件' : '选装软件' }}</span>
                <span v-else>未知</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180px">
              <template slot-scope="scope">
                <el-button type="primary" size="mini" @click="changeModer(scope.row)">修改</el-button>
                <el-button size="mini" type="danger" @click="deleteModer(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
    <el-dialog :close-on-click-modal="false" :close-on-press-escape="false" :visible.sync="moderVisible"
      :title="Action === 1 ? '添加软件' : '修改软件'" v-el-drag-dialog @close="Moder = {}" width="600px">
      <el-form label-width="100px" :rules="rules" :model="Moder" ref="Moder">
        <el-form-item label="软件名称" prop="Descp">
          <el-input placeholder="请输入软件名称" maxlength="64" disabled v-model="Moder.Descp"></el-input>
        </el-form-item>
        <el-form-item label="软件分类" prop="Class">
          <el-select v-model="Moder.Class" placeholder="请选择软件分类" style="width:100%">
            <el-option v-for="(item, index) in partitionList" :key="index" :label="item.Name"
              :value="item.Name"></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="软件安装名" prop="Name">
            <el-input placeholder="请输入软件安装名" oninput="value=value.replace(/[^0-9a-zA-Z.]/g,'')" maxlength="32" v-model="Moder.Name"></el-input>
          </el-form-item> -->
        <el-form-item label="软件版本" prop="Version">
          <el-input placeholder="请输入软件版本" maxlength="32" v-model="Moder.Version"></el-input>
        </el-form-item>
        <!-- <el-form-item label="发布厂商" prop="Factory">
            <el-input placeholder="请输入发布厂商" maxlength="32" v-model="Moder.Factory" disabled></el-input>
          </el-form-item> -->
        <el-form-item label="操作系统" prop="OSClass">
          <el-select v-model="Moder.OSClass" style="width:100%" placeholder="请选择适用系统">
            <el-option label="Windows" value="Windows"></el-option>
            <el-option label="Mac" value="Mac"></el-option>
            <el-option label="Android" value="Android"></el-option>
            <el-option label="Linux" value="Linux"></el-option>
            <el-option label="Other" value="Other"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="系统类型" prop="OSType">
          <el-select v-model="Moder.OSType" style="width:100%" placeholder="请选择系统类型">
            <el-option label="全部" value=""></el-option>
            <el-option label="64" value="64"></el-option>
            <el-option label="32" value="32"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="软件类型" prop="Property">
          <el-select v-model="Moder.Property" style="width:100%" placeholder="请选择软件类型">
            <el-option label="必装软件" :value="1"></el-option>
            <el-option label="非法软件" :value="2"></el-option>
            <el-option label="选装软件" :value="3"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit()">确 定</el-button>
        <el-button type="info" @click="moderVisible = false">取 消</el-button>
      </span>
    </el-dialog>
    <el-dialog top="30px" :close-on-click-modal="false" :close-on-press-escape="false" :visible.sync="reviseModerVisible"
      title="批量修改" :fullscreen="dialogFull" v-el-drag-dialog width="80%">
      <template slot="title">
        <div class="avue-crud__dialog__header">
          <span class="el-dialog__title">
            批量修改
          </span>
          <div class="avue-crud__dialog__menu" @click="dialogFull ? dialogFull = false : dialogFull = true">
            <i class="el-icon-full-screen" v-if="dialogFull == false" />
            <i class="el-icon-copy-document" v-else />
          </div>
        </div>
      </template>
      <el-table stripe border :data="tableMore" style="width: 100%; margin-top: 5px" height="615"
        @cell-mouse-enter="handleCellEnter" @cell-mouse-leave="handleCellLeave" @cell-click="handleCellClick">
        <el-table-column label="序号" width="80" type="index"
          :index='(index) => { return (index + 1) + (pageNum_revise - 1) * pageSize_revise }'> </el-table-column>
        <el-table-column label="软件名称" prop="Descp" show-overflow-tooltip>
          <span class="item" slot-scope="scope">
            <!-- <el-input class="item__input" v-model="scope.row.AppName"  placeholder="请输入软件名称"  maxlength="16"></el-input>
              <p v-if="scope.row.AppName === ''" style="color: #ff4949;font-size: 12px;line-height: 1;padding-top: 4px;">请输入软件名称</p> -->
            <span class="item__txt">{{ scope.row.Descp }}</span>
          </span>
        </el-table-column>
        <el-table-column label="发布厂商" prop="Factory" show-overflow-tooltip>
          <span class="item" slot-scope="scope">
            <!-- <el-input class="item__input" v-model="scope.row.Factory"  placeholder="请输入软件描述" oninput="value=value.replace(/[^0-9a-zA-Z.]/g,'')" maxlength="32"></el-input> -->
            <!-- <p v-if="scope.row.Factory === ''" style="color: #ff4949;font-size: 12px;line-height: 1;padding-top: 4px;">请输入软件安装名</p> -->
            <span class="item__txt">{{ scope.row.Factory }}</span>
          </span>
        </el-table-column>
        <el-table-column label="软件版本" prop="Version" show-overflow-tooltip>
          <div class="item" slot-scope="scope">
            <el-input class="item__input" v-model="scope.row.Version" placeholder="请输入软件版本" maxlength="32"></el-input>
            <!-- <div class="item__txt">{{scope.row.Version}}</div> -->
          </div>
        </el-table-column>
        <el-table-column label="软件分类" prop="Class" show-overflow-tooltip>
          <div class="item" slot-scope="scope">
            <el-select class="item__input" v-model="scope.row.Class" placeholder="请选择软件分类" style="width:100%">
              <el-option v-for="(item, index) in partitionList" :key="index" :label="item.Name"
                :value="item.Name"></el-option>
            </el-select>
          </div>
        </el-table-column>
        <!-- <el-table-column label="软件安装名" prop="Name"   show-overflow-tooltip>
            <div class="item" slot-scope="scope">
              <el-input class="item__input" v-model="scope.row.Name"  placeholder="请输入软件安装名" oninput="value=value.replace(/[^0-9a-zA-Z.]/g,'')" maxlength="32"></el-input>
              <p v-if="scope.row.Name === ''" style="color: #ff4949;font-size: 12px;line-height: 1;padding-top: 4px;">请输入软件安装名</p>
            </div>
          </el-table-column> -->
        <el-table-column label="操作系统" prop="OSClass" show-overflow-tooltip>
          <div class="item" slot-scope="scope">
            <el-select class="item__input" v-model="scope.row.OSClass" @change="handleChange(scope.row)"
              style="width:100%" placeholder="请选择适用系统">
              <el-option label="Windows" value="Windows"></el-option>
              <el-option label="Mac" value="Mac"></el-option>
              <el-option label="Android" value="Android"></el-option>
              <el-option label="Linux" value="Linux"></el-option>
              <el-option label="Other" value="Other"></el-option>
            </el-select>
          </div>
        </el-table-column>
        <el-table-column label="系统类型" prop="OSType" show-overflow-tooltip>
          <div class="item" slot-scope="scope">
            <el-select class="item__input" v-model="scope.row.OSType" style="width:100%" placeholder="请选择系统类型">
              <el-option label="全部" value=""></el-option>
              <el-option label="64" value="64"></el-option>
              <el-option label="32" value="32"></el-option>
            </el-select>
          </div>
        </el-table-column>
        <el-table-column label="软件类型" prop="Property" show-overflow-tooltip>
          <div class="item" slot-scope="scope">
            <el-select class="item__input" v-model="scope.row.Property" style="width:100%" placeholder="请选择软件类型">
              <el-option label="必装软件" :value="1"></el-option>
              <el-option label="非法软件" :value="2"></el-option>
              <el-option label="选装软件" :value="3"></el-option>
            </el-select>
          </div>
        </el-table-column>
      </el-table>
      <el-pagination @size-change="handleSizeChange_revise" @current-change="handleCurrentChange_revise"
        :current-page=pageNum_revise :page-size=pageSize_revise background
        layout="total, prev, pager, sizes, next, jumper" :total="Total_revise">
      </el-pagination>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitRevise()">确 定</el-button>
        <el-button type="info" @click="reviseModerVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { connrequest } from '@/api/firstPage'
import elDragDialog from "@/directive/el-drag-dialog";
import partitionTree from "@/components/partitionTree";
export default {
  directives: { elDragDialog },
  components: {
    partitionTree
  },
  data() {
    return {
      pageNum: 1,
      pageSize: 10,
      pageNum_revise: 1,
      pageSize_revise: 10,
      Total_revise: 0,
      containerWidth: 'calc(100% - 275px)',
      tableData: [],
      tableMore: [],
      nodeData: [],
      defaultProps: {
        children: 'Class',
        label: 'Name',
        Count: 'Count'
      },
      Action: 1,
      Moder: {},
      moderVisible: false,
      reSource: [],
      partitionList: [],
      rules: {
        AppName: [
          { required: true, message: '请输入软件名称', trigger: 'blur' }
        ],
        Class: [
          { required: true, message: '请选择软件分类', trigger: 'change' }
        ],
        ExeName: [
          { required: true, message: '请输入执行文件', trigger: 'blur' }
        ]
      },
      dialogFull: false,
      reviseModerVisible: false,
      // 需要编辑的属性
      editProp: ['AppClass', 'ExeName', 'Class'],
      clickCellMap: {},
      multable: []
    }
  },
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.getData()
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {
  },
  methods: {
    handleChange(row) {

    },
    async getData() {
      const res = await connrequest('GetDictInstallAppTree')
      let partitionList = []
      res.Data.Name = res.Data.RootName //因为后端返回的所有分区名字叫RootName，子菜单又叫Name, 这里做个转换
      res.Data.disabled = true
      res.Data.Class.map(item => {
        partitionList.push(item)
      })
      this.nodeData = [res.Data]
      this.partitionList = partitionList
      this.GetDictArea(this.PrimName)
    },
    async GetDictArea(Name) {
      const data = {
        Filter: {
          Name: Name || ''
        }
      }
      const res = await connrequest('GetDictInstallApp', data)
      this.tableData = res.Data
      if (Name === '' || Name === undefined) {  //获取所有编码
        let partitionNumber = []
        res.Data.map(item => {
          partitionNumber.push(item.AreaCode)
        })
        this.partitionNumber = partitionNumber
      }
    },
    handleNodeClick(nodeData) {
      const { data } = nodeData
      let PrimName = data.Name === '所有软件' ? '' : data.Name
      this.PrimName = PrimName
      this.$set(this.Moder, 'PrimArea', PrimName)
      this.GetDictArea(PrimName)
    },
    async submitTemplete(node) {
      const data = {
        Data: {
          Action: node.Action,
          Detail: {
            Name: node.DepartmentName
          }
        }
      }
      const res = await connrequest('EditDictInstallAppTree', data)
      if (res.Status.StatusCode === 0) {
        this.$message.success(node.Action === 1 ? '新增成功' : '修改成功')
        this.$refs.partitionTree.departmentDialog = false
        this.getData()
      }
    },
    async deleteNode(node) {
      if (node.Count > 0) {
        this.$message.error('该软件下还有数据，请清空后再删除')
        return
      }
      const data = {
        Data: {
          Action: 3,
          Detail: {
            Name: node.Name
          }
        }
      }
      const res = await connrequest('EditDictInstallAppTree', data)
      if (res.Status.StatusCode === 0) {
        this.$message.success('删除成功')
        this.getData()
      }
    },
    addModer() {
      this.Action = 1
      this.Moder = { 
        Class: this.partitionList[0]?.Name,
      }
      this.$nextTick(() => {
        this.$refs.Moder.clearValidate();
      })
      this.moderVisible = true
    },
    changeModer(row) {
      this.Action = 2
      this.Moder = { ...row }
      this.moderVisible = true
    },
    deleteModer(row) {
      this.$confirm('此操作将永久删除该软件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const data = {
          Data: {
            Action: 3,
            Detail: { ...row }
          }
        }
        const res = await connrequest('EditDictInstallApp', data)
        if (res.Status.StatusCode === 0) {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.getData()
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    async submit() {
      this.$refs['Moder'].validate(async (valid) => {
        if (valid) {
          if (this.tableData.findIndex(item => item.Descp === this.Moder.Descp) !== -1 && this.Action === 1) {
            this.$message.error(`软件名称 ${this.Moder.Descp} 已经存在`)
            return false
          }
          const data = {
            Data: {
              Action: this.Action,
              Detail: {
                Descp: this.Moder.Descp,
                Class: this.Moder.Class,
                Factory: this.Moder.Factory,
                Version: this.Moder.Version,
                OSClass: this.Moder.OSClass,
                OSType: this.Moder.OSType,
                Property: this.Moder.Property
              }
            }
          }
          const res = await connrequest('EditDictInstallApp', data)
          if (res.Status.StatusCode === 0) {
            this.$message.success(this.Action === 1 ? '新增成功' : '修改成功')
            this.moderVisible = false
            this.getData()
          }
        }
      })
    },
    reviseStart() {
      this.multable = []
      this.tableMore = []
      this.pageNum_revise = 1
      this.pageSize_revise = 10
      this.reviseModer()
      this.reviseModerVisible = true
    },
    async reviseModer() {
      const data = {
        Paging: {
          QueryPageNo: this.pageNum_revise,
          QueryPageLength: this.pageSize_revise
        }
      }
      const res = await connrequest('GetUnknownDictSoftware', data)
      this.tableMore = res.Data || []
      this.tableMore.forEach(item => {
        this.$set(item, 'OSClass', item.OSClass || 'Windows')
        this.$set(item, 'OSType', item.OSType || '')
      })
      this.processArray()

      this.Total_revise = res.Paging.TotalCount
    },
    processArray() {
      // 找到存在于 array2 中且存在于 array1 中的值
      const commonObjects = this.multable.filter(obj1 => { return this.tableMore.find(obj2 => obj2.Descp === obj1.Descp); });
      // if(commonObjects.length == 0){
      // 找到存在于 array2 中但不存在于 array1 中的值
      const additionalValues = this.tableMore.filter(item => { return !this.multable.map(obj => obj.Descp).includes(item.Descp); });
      this.multable.push(...additionalValues)
      // }
      // else{
      // 创建描述值到新值的映射
      this.tableMore = this.tableMore.map(obj2 => {
        let matchedObj = commonObjects.find(obj1 => obj1.Descp === obj2.Descp);
        return matchedObj ? matchedObj : obj2;
      });
      // }
    },
    async submitRevise() {
      this.filterArray()
      const data = {
        Data: [...this.multable]
      }
      if (data.Data.length == 0) {
        this.reviseModerVisible = false;
        return
      }
      else {
        const res = await connrequest('SetUnknownDictSoftware', data)
        if (res.Status.StatusCode === 0) {
          this.$message.success('修改成功')
          this.getData()
          this.reviseModerVisible = false;
        }
      }
    },
    handleSizeChange_revise(pageSize) {
      this.pageSize_revise = pageSize
      this.pageNum_revise = 1
      this.filterArray()
      this.reviseModer()
    },
    handleCurrentChange_revise(pageNum) {
      this.pageNum_revise = pageNum
      this.filterArray()
      this.reviseModer()
    },
    // 将在当前页处理过的数据保存到总的数组中去
    filterArray() {
      this.multable = this.multable.map(obj2 => {
        let matchedObj = this.tableMore.find(obj1 => obj1.Descp === obj2.Descp);
        return matchedObj ? matchedObj : obj2;
      });
    },
    /** 鼠标移入cell */
    handleCellEnter(row, column, cell, event) {
      // const property = column.property
      // if (property === 'date' || property === 'name' || property === 'food') {
      //   cell.querySelector('.item__txt').classList.add('item__txt--hover')
      // }
    },
    // /** 鼠标移出cell */
    handleCellLeave(row, column, cell, event) {
      // const property = column.property
      // if (this.editProp.includes(property)) {
      //   cell.querySelector('.item__txt').classList.remove('item__txt--hover')
      // }
    },
    /** 点击cell */
    handleCellClick(row, column, cell, event) {
      const property = column.property
      if (this.editProp.includes(property)) {
        // 保存cell
        this.saveCellClick(row, cell)
        // cell.querySelector('.item__txt').style.display = 'none'
        cell.querySelector('.item__input').style.display = 'block'
        cell.querySelector('input').focus()
      }
    },
    /** 取消编辑状态 */
    cancelEditable(cell) {
      // cell.querySelector('.item__txt').style.display = 'block'
      cell.querySelector('.item__input').style.display = 'none'
    },
    /** 保存进入编辑的cell */
    saveCellClick(row, cell) {
      const id = row.id
      if (this.clickCellMap[id] !== undefined) {
        if (!this.clickCellMap[id].includes(cell)) {
          this.clickCellMap[id].push(cell)
        }
      } else {
        this.clickCellMap[id] = [cell]
      }
    },
    toggleVisibility(isHidden) {
      if (isHidden)
        this.containerWidth = '100%';
      else
        this.containerWidth = 'calc(100% - 275px)';
    }
  }
};
</script>
<style scoped>
.box {
  background-color: lightblue;
  transition: width 0.5s;
  /* 添加过渡动画 */
}

/* dialog header */
.avue-crud__dialog__header {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  -webkit-box-pack: justify;
  -ms-flex-pack: justify;
  justify-content: space-between;
}

.el-dialog__title {
  color: rgba(0, 0, 0, .85);
  font-weight: 500;
  word-wrap: break-word;
}

.avue-crud__dialog__menu {
  padding-right: 35px;
  float: left;
}

.avue-crud__dialog__menu i {
  color: white;
  font-size: 15px;
}

.el-icon-full-screen {
  cursor: pointer;
}

.el-icon-full-screen:before {
  content: "\e719";
}

.el-icon-copy-document {
  cursor: pointer;
}
</style>
